import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'

export const useInterceptorStore = defineStore('interceptor', () => {
  // 状态
  const requests = ref([])
  const interceptedRequests = ref([])
  const isEnabled = ref(true)
  const extensionEnabled = ref(true)
  
  // 从 localStorage 加载数据
  const loadFromSession = (key, defaultValue) => {
    try {
      const stored = localStorage.getItem(key)
      const result = stored ? JSON.parse(stored) : defaultValue
      console.log(`已加载 ${key}:`, result)
      return result
    } catch (error) {
      console.error(`Error loading ${key} from localStorage:`, error)
      return defaultValue
    }
  }

  // 搜索关键词
  const searchKeyword = ref('')
  const interceptedSearchKeyword = ref('')

  // 批量禁用模式
  const batchDisableEnabled = ref(loadFromSession('batch_disable_enabled', false))

  // 启用拦截的网站列表
  const enabledWebsites = ref(loadFromSession('enabled_websites', []))

  // 保存数据到 localStorage
  const saveToSession = (key, value) => {
    try {
      localStorage.setItem(key, JSON.stringify(value))
      console.log(`已保存 ${key}:`, value)
    } catch (error) {
      console.error(`Error saving ${key} to localStorage:`, error)
    }
  }

  // 从 background 加载数据
  const loadData = async () => {
    try {
      console.log('Loading data from background...')
      const response = await chrome.runtime.sendMessage({ type: 'GET_DATA' })
      if (response) {
        console.log('Data loaded:', response)
        requests.value = response.requests || []
        interceptedRequests.value = response.intercepted || []
        isEnabled.value = response.isEnabled !== false

        console.log('Data loaded successfully:', {
          requests: requests.value.length,
          intercepted: interceptedRequests.value.length,
          enabled: isEnabled.value
        })
      } else {
        console.warn('No data received from background')
      }
    } catch (error) {
      console.error('加载数据失败:', error)
      // 如果加载失败，尝试从本地存储加载
      loadFromSessionStorage()
    }

    // 确保enabledWebsites从localStorage重新加载（如果还没有数据的话）
    if (enabledWebsites.value.length === 0) {
      const savedWebsites = loadFromSession('enabled_websites', [])
      enabledWebsites.value = savedWebsites
    }
    console.log('🌐 当前启用的网站列表:', enabledWebsites.value)
  }

  // 从 sessionStorage 加载数据
  const loadFromSessionStorage = () => {
    try {
      console.log('Loading data from session storage...')
      requests.value = loadFromSession('interceptor_requests', [])
      interceptedRequests.value = loadFromSession('interceptor_intercepted', [])
      isEnabled.value = loadFromSession('interceptor_enabled', true)
      batchDisableEnabled.value = loadFromSession('batch_disable_enabled', false)

      console.log('Session data loaded:', {
        requests: requests.value.length,
        intercepted: interceptedRequests.value.length,
        batchDisableEnabled: batchDisableEnabled.value
      })
    } catch (error) {
      console.error('Failed to load from session:', error)
    }
  }

  // 保存拦截数据
  const saveInterceptedData = async () => {
    try {
      console.log('💾 保存拦截数据:', interceptedRequests.value.length, '条规则')
      saveToSession('interceptor_intercepted', interceptedRequests.value)
      await chrome.runtime.sendMessage({
        type: 'SAVE_INTERCEPTED',
        data: interceptedRequests.value
      })
      console.log('✅ 拦截数据保存成功')
    } catch (error) {
      console.error('保存拦截数据失败:', error)
    }
  }

  // 切换启用状态
  const toggleEnabled = async () => {
    try {
      isEnabled.value = !isEnabled.value
      saveToSession('interceptor_enabled', isEnabled.value)
      
      await chrome.runtime.sendMessage({
        type: 'TOGGLE_ENABLED',
        enabled: isEnabled.value
      })
      
      // 通知 content script 更新状态
      updateContentScript()
    } catch (error) {
      console.error('切换启用状态失败:', error)
    }
  }

  // 更新 content script (只在popup环境中使用)
  const updateContentScript = () => {
    // 检查是否在popup环境中
    if (typeof chrome !== 'undefined' && chrome.tabs && chrome.tabs.query) {
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs[0]) {
          chrome.tabs.sendMessage(tabs[0].id, {
            type: 'UPDATE_INTERCEPT_DATA',
            data: {
              enabled: isEnabled.value,
              intercepted: interceptedRequests.value,
              batchDisableEnabled: batchDisableEnabled.value
            }
          }).catch(() => {
            // 忽略错误，可能是在不支持的页面
          })
        }
      })
    } else {
      // 在content script环境中，使用updateInjectedScript
      updateInjectedScript()
    }
  }

  // 更新注入脚本（用于content script）
  const updateInjectedScript = (data) => {
    const updateData = data || {
      enabled: isEnabled.value,
      intercepted: interceptedRequests.value,
      batchDisableEnabled: batchDisableEnabled.value
    }

    // 序列化数据以确保可以被postMessage克隆
    const serializedData = JSON.parse(JSON.stringify(updateData))

    window.postMessage({
      type: 'UPDATE_INTERCEPT_DATA',
      data: serializedData
    }, '*')
  }

  // 获取过滤后的请求列表
  const getFilteredRequests = () => {
    if (!searchKeyword.value || !searchKeyword.value.trim()) {
      return requests.value
    }

    const keyword = searchKeyword.value.toLowerCase()
    return requests.value.filter(request =>
      request.url.toLowerCase().includes(keyword) ||
      request.method.toLowerCase().includes(keyword)
    )
  }

  // 获取过滤后的拦截列表
  const getFilteredIntercepted = () => {
    if (!interceptedSearchKeyword.value || !interceptedSearchKeyword.value.trim()) {
      return interceptedRequests.value
    }

    const keyword = interceptedSearchKeyword.value.toLowerCase()
    return interceptedRequests.value.filter(item =>
      item.url.toLowerCase().includes(keyword) ||
      item.method.toLowerCase().includes(keyword)
    )
  }

  // 添加请求
  const addRequest = (request) => {
    // 过滤掉插件自身和系统请求
    if (request.url.includes('chrome-extension://') ||
        request.url.includes('chrome://') ||
        request.url.includes('data:') ||
        request.url.includes('blob:')) {
      return
    }

    console.log('Adding request:', request)

    // 添加到请求列表
    requests.value.unshift({
      id: Date.now() + Math.random(),
      ...request
    })

    // 只保留最近50个请求
    if (requests.value.length > 50) {
      requests.value = requests.value.slice(0, 50)
    }

    // 保存到 sessionStorage
    saveToSession('interceptor_requests', requests.value)
  }

  // 清空请求列表
  const clearRequests = async () => {
    requests.value = []
    saveToSession('interceptor_requests', [])

    try {
      await chrome.runtime.sendMessage({ type: 'CLEAR_REQUESTS' })
    } catch (error) {
      console.error('清空请求列表失败:', error)
    }
  }

  // 清空拦截列表
  const clearInterceptedRequests = async () => {
    interceptedRequests.value = []
    saveToSession('interceptor_intercepted', [])

    try {
      await chrome.runtime.sendMessage({
        type: 'CLEAR_INTERCEPTED'
      })
    } catch (error) {
      console.error('清空拦截列表失败:', error)
    }

    // 更新注入脚本
    updateInjectedScript()
  }

  // 添加拦截规则
  const addInterceptRule = (rule) => {
    interceptedRequests.value.push(rule)
    saveInterceptedData()
    updateContentScript()
  }

  // 删除拦截规则
  const removeInterceptRule = (id) => {
    const index = interceptedRequests.value.findIndex(item => item.id === id)
    if (index !== -1) {
      interceptedRequests.value.splice(index, 1)
      saveInterceptedData()
      updateContentScript()
    }
  }

  // 更新拦截规则
  const updateInterceptRule = (id, updates) => {
    const item = interceptedRequests.value.find(item => item.id === id)
    if (item) {
      Object.assign(item, updates)
      saveInterceptedData()
      updateContentScript()
    }
  }

  // 切换拦截规则启用状态
  const toggleInterceptRule = (id) => {
    const item = interceptedRequests.value.find(item => item.id === id)
    if (item) {
      item.enabled = !item.enabled
      saveInterceptedData()
      updateContentScript()
    }
  }

  // 切换批量禁用模式
  const toggleBatchDisable = (enabled) => {
    batchDisableEnabled.value = enabled

    // 保存批量禁用状态到 sessionStorage
    saveToSession('batch_disable_enabled', enabled)

    // 更新注入脚本（传递批量禁用状态）
    updateInjectedScript()
  }

  // 获取当前活动标签页的域名
  const getCurrentDomain = async () => {
    try {
      // 在popup环境中，需要通过chrome API获取当前活动标签页
      if (typeof chrome !== 'undefined' && chrome.tabs) {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
        if (tab && tab.url) {
          return new URL(tab.url).hostname
        }
      }
      // 在content script环境中，直接使用window.location
      return new URL(window.location.href).hostname
    } catch (error) {
      console.warn('获取域名失败:', error)
      return 'unknown'
    }
  }

  // 检查网站是否启用拦截
  const isWebsiteEnabled = (domain) => {
    return enabledWebsites.value.includes(domain)
  }

  // 添加网站到拦截列表
  const addWebsite = (domain) => {
    if (!enabledWebsites.value.includes(domain)) {
      enabledWebsites.value.push(domain)
      saveToSession('enabled_websites', enabledWebsites.value)
    }
  }

  // 从拦截列表移除网站
  const removeWebsite = (domain) => {
    const index = enabledWebsites.value.indexOf(domain)
    if (index > -1) {
      enabledWebsites.value.splice(index, 1)
      saveToSession('enabled_websites', enabledWebsites.value)
    }
  }

  // 切换网站拦截状态
  const toggleWebsite = (domain) => {
    if (isWebsiteEnabled(domain)) {
      removeWebsite(domain)
    } else {
      addWebsite(domain)
    }
  }

  // 检查当前网站是否应该显示悬浮按钮
  const shouldShowFloatingButton = () => {
    const currentDomain = getCurrentDomain()
    return isWebsiteEnabled(currentDomain)
  }

  return {
    // 状态
    requests,
    interceptedRequests,
    isEnabled,
    extensionEnabled,
    searchKeyword,
    interceptedSearchKeyword,
    batchDisableEnabled,
    enabledWebsites,

    // 方法
    loadData,
    loadFromSessionStorage,
    saveInterceptedData,
    toggleEnabled,
    updateContentScript,
    updateInjectedScript,
    addRequest,
    clearRequests,
    clearInterceptedRequests,
    addInterceptRule,
    removeInterceptRule,
    updateInterceptRule,
    toggleInterceptRule,
    toggleBatchDisable,
    loadFromSession,
    saveToSession,
    getFilteredRequests,
    getFilteredIntercepted,

    // 网站管理方法
    getCurrentDomain,
    isWebsiteEnabled,
    addWebsite,
    removeWebsite,
    toggleWebsite,
    shouldShowFloatingButton
  }
})
